package com.patzn.osgi.email.client;

import com.patzn.osgi.email.api.IEmailService;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;

import java.util.Arrays;
import java.util.Collection;

public class ClientActivator implements BundleActivator {
    @Override
    public void start(BundleContext bundleContext) throws Exception {
        ServiceReference<?>[] allServiceReferences = bundleContext.getAllServiceReferences(IEmailService.class.getName(), null);
        if (null != allServiceReferences) {
            System.out.println("服务引用：" + allServiceReferences.length + " 个");

            for (ServiceReference<?> serviceReference : allServiceReferences) {
                IEmailService iEmailService = (IEmailService) bundleContext.getService(serviceReference);
                iEmailService.send("123@qdhlm.cn", "OSGI", "Hello OSGI");
            }
        }

        System.out.println("======== 获取单个服务 ========");

        ServiceReference<?> serviceReference = bundleContext.getServiceReference(IEmailService.class.getName());
        if (null != serviceReference) {
            IEmailService iEmailService = (IEmailService) bundleContext.getService(serviceReference);
            iEmailService.send("456@qdhlm.cn", "OSGI", "Hello OSGI");

            System.out.println("服务属性：" + Arrays.toString(serviceReference.getPropertyKeys()));
        }

        // 139
        System.out.println("获取139服务：");
        getService(bundleContext, "139");

        // 163
        System.out.println("获取163服务：");
        getService(bundleContext, "163");
    }

    public void getService(BundleContext bundleContext, String vendor) throws InvalidSyntaxException {
        String filter = "(vendor=" + vendor + ")";
        Collection<ServiceReference<IEmailService>> serviceReferences = bundleContext.getServiceReferences(IEmailService.class, filter);
        if (null != serviceReferences) {
            for (ServiceReference<IEmailService> serviceReference : serviceReferences) {
                IEmailService iEmailService = bundleContext.getService(serviceReference);
                iEmailService.send("789@qdhlm.cn", "OSGI", "Hello OSGI");
            }
        }
    }

    @Override
    public void stop(BundleContext bundleContext) throws Exception {

    }
}
